var userId;
window.onload = async function () {
    await findUser();
    findProduct(1);
};

//查询是否登录，展示不一样的数据信息
async function findUser() {
    var user = await ajaxGet("/user/getUser");
    userId = user.userId;
    if (user == ""){
        $("infoDiv").innerHTML = "你好 ,请先<a href='/html/login.html'>登录</a>";
    }else {
        $("infoDiv").innerHTML = `你好 ,${user.username}`;
    }
}

//查找所有的商品信息，展示数据
async function findProduct(pageNo) {
    let product = await ajaxGet("/product/findByItem",{
        pageNo:pageNo,
        status: "上架",
        name:$("product").value,
        start:$("start").value,
        end:$("end").value
    });

    //生成产品详细信息
    let str = "";
    for (let i = 0; i < product.list.length; i++) {
        let info = product.list[i];
        str += `<div class="pro"> 
                    <img src="/html/img/${info.imgPath}" style="width:200px;height: 250px;"><br>
                    <span>${info.productName}</span><br>
                    <span>单价: ￥ ${info.productPrice}</span><br>
                    <span>已售出${info.num}件</span><br>
                    <input type="button" value="查看" onclick="query(${info.productId})">
                    <input type="button" value="购买" onclick="buy(${info.productId})">
                </div>`;
    }
    $("productDiv").innerHTML = str;

    //生成页码超链接
    let a = "";
    for (let i = 1; i <= product.pages; i++) {
         a += `<a style="margin-left: 20px;text-decoration: none" href="javascript:findProduct(${i})">${i}</a>`;
    }
    $("pageDiv").innerHTML = a
}

//跳转到商品详情界面，把商品id带过去
function query(productId) {
    location.href = "/html/findProduct.html?id="+productId;
}

//购买方法,添加购物车，成功跳转到购物车界面
async function buy(productId) {
    var info = await ajaxGet("/shop/add",{
        productId:productId
    });
    if (info == "ok"){
        location.href = "/html/custom/shop.html";
    }else {
        alert("添加购物车失败, 请重试")
    }
}